package com.dmgis.qxfw.dataservice.bigdata.controller;

import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.common.util.DateTime;
import com.dmgis.qxfw.dataservice.businessservice.common.util.FileUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.StringUtil;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.github.kevinsawicki.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Controller
public class DownLdController {

	//MongoService1 ms = new MongoService1();
	FileRequestService ms = new FileRequestService();
	private  final String operatingSystem;

	@Autowired
	public DownLdController(String operatingSystem) {
		this.operatingSystem = operatingSystem;
	}


	@RequestMapping(value = "/dataservicedownload", method = RequestMethod.GET)
	@ResponseBody
	public Object dataservicedownload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String serviceFilePath = "";
		String collectionName = request.getParameter("collectionName");
		String resultType = request.getParameter("resultType");
		if (StringUtil.IsNullOrEmpty(resultType)) {
			resultType = "binary";// 方便图片处理
		}
		ResponseEntity<byte[]> result = null;
		if (StringUtil.IsNullOrEmpty(collectionName)) {
			return "collectionName should not be empty";
		}
		// 雷达
		if (collectionName.startsWith("ld")) {
			serviceFilePath = dataserviceDownLoadRadar(request, collectionName);
		}

		else if (collectionName.startsWith("yt")) {
			serviceFilePath = dataserviceDownLoadYt(request, collectionName);
		} else {
			serviceFilePath = dataserviceDownLoadFile(request, collectionName, resultType);// resultType==url时，返回临时文件网络路径，否则返回服务器本地路径
		}
		if (!serviceFilePath.equals("")) {
			if ("url".equals(resultType)) {
				return serviceFilePath;
			} else {
				if ("binary".equals(resultType)) {
					File file = new File(serviceFilePath);
					// 读取目标文件为二进制数组
					byte[] fileByte = FileCopyUtils.copyToByteArray(file);
					// 创建ResponseEntity对象
					result = new ResponseEntity<byte[]>(fileByte, HttpStatus.CREATED);
				} else if ("download".equals(resultType)) {
					File file = new File(serviceFilePath);
					response.reset();
					response.setContentType("application/octet-stream");
					// 3.设置content-disposition响应头控制浏览器以下载的形式打开文件
					response.setHeader("content-disposition",
							"attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
					InputStream in = new FileInputStream(file);// 获取文件输入流
					int len = 0;
					byte[] buffer = new byte[1024];
					OutputStream out = response.getOutputStream();
					while ((len = in.read(buffer)) > 0) {
						out.write(buffer, 0, len);// 将缓冲区的数据输出到客户端浏览器
					}
					in.close();
				}
				return result;
			}
		} else {
			return "";
		}

	}

	/**
	 * 雷达图下载
	 * 
	 * @param request
	 * @param collectionName
	 * @return
	 * @throws ParseException
	 * @author dsq
	 * @date 2018年10月18日
	 */
	private String dataserviceDownLoadRadar(HttpServletRequest request, String collectionName) throws ParseException {
		String serviceFilePath = "";
		String fileName = "";
		String stationid = request.getParameter("stationid").trim();
		String datechar = request.getParameter("datechar").trim();
		DateTime dateTime = DateTime.parseDateTime(datechar);
		String timechar = request.getParameter("timechar").trim();
		String ldtype = request.getParameter("ldtype").trim();
		String elevation = request.getParameter("elevation").trim();
		if (collectionName.equals("ld_file")) {
			fileName = DbConfig.getRadarFileName(ldtype, elevation.toString(), stationid, dateTime.toDate(), timechar);
		}
		if (collectionName.equals("ld_png_file")) {
			fileName = DbConfig.getRadarFileName(ldtype, elevation.toString(), stationid, dateTime.toDate(), timechar)
					+ ".png";
		}
		if (collectionName.equals("ld_jpg_file")) {
			fileName = DbConfig.getRadarFileName(ldtype, elevation.toString(), stationid, dateTime.toDate(), timechar)
					+ ".jpg";
		}
		if (collectionName.equals("ld_gt_file")) {
			fileName = DbConfig.getRadarFileName(ldtype, elevation.toString(), stationid, dateTime.toDate(), timechar)
					+ "_gt.jpg";
		}


		String urlpath ;
		if (operatingSystem.equals("Windows")){
			urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Radar\\";// 临时文件目录
		}else {
			urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Radar/";// 临时文件目录
		}

		serviceFilePath = urlpath + fileName;// 服务器文件

		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

		// 如果目录中不存在文件，下载雷达文件到temp目录
		File serviceFile = new File(serviceFilePath);// 服务器文件
		if (!serviceFile.exists()) {// 把文件上传到服务器
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("datechar", dateTime.toDateTimeString("yyyy-MM-dd"));
			map.put("stationid", stationid);
			map.put("elevation", elevation);
			map.put("ldtype", ldtype);
			map.put("timechar", timechar);
			map.put("collectionName", collectionName);
			byte[] data = ms.selectData(map);
			if (data==null || data.length <= 0) {
				serviceFilePath = "";
			} else {
				FileUtil.bytesToFile(data, serviceFilePath);
			}
		}
		return serviceFilePath;
	}

	/**
	 * 云图下载
	 * 
	 * @param request
	 * @param collectionName
	 * @return
	 * @throws ParseException
	 * @author dsq
	 * @date 2018年10月18日
	 */
	private String dataserviceDownLoadYt(HttpServletRequest request, String collectionName) throws ParseException {
		String fileName = "";
		String serviceFilePath = "";
		String datechar = request.getParameter("datechar").trim();
		DateTime dateTime = DateTime.parseDateTime(datechar);
		String timechar = request.getParameter("timechar").trim();
		String yttype = request.getParameter("yttype").trim();
		if (collectionName.equals("yt_file")) {
			fileName = DbConfig.getYtFileName(yttype, dateTime.toDate(), timechar);
		}
		if (collectionName.equals("yt_png_file")) {
			fileName = DbConfig.getYtFileName(yttype, dateTime.toDate(), timechar) + ".png";
		}
		if (collectionName.equals("yt_jpg_file")) {
			fileName = DbConfig.getYtFileName(yttype, dateTime.toDate(), timechar) + ".jpg";
		}
		String urlpath ;
		if (operatingSystem.equals("Windows")){
			urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Cloud\\";// 临时文件目录
		}else {
			urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Cloud/";// 临时文件目录
		}

		serviceFilePath = urlpath + fileName;// 服务器文件

		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

		// 如果目录中不存在文件，下载雷达文件到temp目录
		File serviceFile = new File(serviceFilePath);// 服务器文件
		if (!serviceFile.exists()) {// 把文件上传到服务器
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("datechar", dateTime.toDateTimeString("yyyy-MM-dd"));
			map1.put("yttype", yttype);
			map1.put("timechar", timechar);
			map1.put("collectionName", collectionName);
			byte[] data = ms.selectData(map1);
			if (data==null || data.length <= 0) {
				serviceFilePath = "";
			} else {
				FileUtil.bytesToFile(data, serviceFilePath);
			}
		}
		return serviceFilePath;
	}

	/**
	 * 图片下载
	 * 
	 * @param request
	 * @param collectionName
	 * @return
	 * @author dsq
	 * @date 2018年10月18日
	 */
	// private String DownLoadImage(HttpServletRequest request, String
	// collectionName) {
	// String fileName = "";
	// String serviceFilePath = "";
	// Enumeration<String> em = request.getParameterNames();
	// Map<String, Object> queryMap = new HashMap<String, Object>();
	// while (em.hasMoreElements()) {
	// String name = (String) em.nextElement();
	// String value = request.getParameter(name);
	// if ("collectionName".equals(name)) {
	// collectionName = value;
	// } else {
	// queryMap.put(name, value.trim());// 去除空格
	// fileName += value + "_";
	// }
	// }
	// // 下载
	// fileName = StringUtil.trimEnd(fileName, '_') + ".jpg";
	// String urlpath =
	// request.getSession().getServletContext().getRealPath("/") +
	// "Temp\\Image\\";// 临时文件目录
	// serviceFilePath = urlpath + fileName;// 服务器文件
	// FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
	// FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
	// // 如果目录中不存在文件，下载雷达文件到temp目录
	// File serviceFile = new File(serviceFilePath);// 服务器文件
	// if (!serviceFile.exists()) {// 把文件上传到服务器
	// byte[] data = HttpRequest.get(DbConfig.mongoSelectUrl, queryMap,
	// true).bytes();
	// if (data.equals("[]") || data.length <= 0) {
	// serviceFilePath = "";
	// } else {
	// FileUtil.bytesToFile(data, serviceFilePath);
	// }
	// }
	// return serviceFilePath;
	// }

	/**
	 * 文件下载
	 * 
	 * @param request
	 * @param collectionName
	 * @param
	 * @return
	 * @author dsq
	 * @throws ParseException 
	 * @date 2018年10月22日
	 */
	private String dataserviceDownLoadFile(HttpServletRequest request, String collectionName, String resultType) throws ParseException {
		String fileName = "";
		String serviceFilePath = "";
		Enumeration<String> em = request.getParameterNames();
		Map<String, Object> queryMap = new HashMap<String, Object>();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			if ("collectionName".equals(name)) {
				collectionName = value;
			}
			if (!name.equals("resultType")) {// 过滤特殊字符
				queryMap.put(name, value.trim());// 去除空格
				if("datechar".equals(name)){
					fileName += DateTime.parseDateTime(value).toDateTimeString("yyyyMMddHHmmss") + "_";
				}
				else {
					fileName += value + "_";
				}
			}
		}
		String fileType = collectionName.split("_")[0];
		if (fileType.equals("image")) {
			fileType = "jpg";
		}
		if (collectionName.contains("png")) {
			fileType = "png";
		}
		if (collectionName.contains("jpg")) {
			fileType = "png";
		}
		if (collectionName.contains("bmp")) {
			fileType = "bmp";
		}
		if (fileType.equals("excel")) {
			fileType = "xlsx";
		}
		// 下载
		fileName = StringUtil.trimEnd(fileName, '_') + "." + fileType;
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/Temp/File/";
		String serviceUrl = basePath + fileName;

		String urlpath ;
		if (operatingSystem.equals("Windows")){
			urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\File\\";
		}else {
			urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/File/";
		}

		serviceFilePath = urlpath + fileName;// 服务器文件
		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
		// 如果目录中不存在文件，下载雷达文件到temp目录
		File serviceFile = new File(serviceFilePath);// 服务器文件
		if (!serviceFile.exists()) {// 把文件上传到服务器{
			byte[] data = ms.selectData(queryMap);
			if (data==null || data.length <= 0) {
				serviceFilePath = "";
			} else {
				if (fileType.equals("txt")) {
					try {
						FileUtil.writeLog(serviceFilePath, new String(data, FileUtil.getCodeType(data)));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				else{FileUtil.bytesToFile(data, serviceFilePath);}
			}
		}
		if ("url".equals(resultType) && !serviceFilePath.equals("")) {
			serviceFilePath = serviceUrl;
		}
		return serviceFilePath;
	}

	/**
	 * 雷达图下载
	 *
	 * @param request
	 * @param collectionName
	 * @return
	 * @throws ParseException
	 * @author dsq
	 * @date 2018年10月18日
	 */
	private String DownLoadRadar(HttpServletRequest request, String collectionName) throws ParseException {
		String serviceFilePath = "";
		String fileName = "";
		String stationid = request.getParameter("stationid").trim();
		String datechar = request.getParameter("datechar").trim();
		DateTime dateTime = DateTime.parseDateTime(datechar);
		String timechar = request.getParameter("timechar").trim();
		String ldtype = request.getParameter("ldtype").trim();
		String elevation = request.getParameter("elevation").trim();
		if (collectionName.equals("ld_file")) {
			fileName = DbConfig.getRadarFileName(ldtype, elevation.toString(), stationid, dateTime.toDate(), timechar);
		}
		if (collectionName.equals("ld_png_file")) {
			fileName = DbConfig.getRadarFileName(ldtype, elevation.toString(), stationid, dateTime.toDate(), timechar)
					+ ".png";
		}
		if (collectionName.equals("ld_jpg_file")) {
			fileName = DbConfig.getRadarFileName(ldtype, elevation.toString(), stationid, dateTime.toDate(), timechar)
					+ ".jpg";
		}
		if (collectionName.equals("ld_gt_file")) {
			fileName = DbConfig.getRadarFileName(ldtype, elevation.toString(), stationid, dateTime.toDate(), timechar)
					+ "_gt.jpg";
		}
		String urlpath ;
		if (operatingSystem.equals("Windows")){
			 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Radar\\";// 临时文件目录
		}else {
			urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Radar/";// 临时文件目录
		}

		serviceFilePath = urlpath + fileName;// 服务器文件

		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

		// 如果目录中不存在文件，下载雷达文件到temp目录
		File serviceFile = new File(serviceFilePath);// 服务器文件
		if (!serviceFile.exists()) {// 把文件上传到服务器
			Map<String, String> map = new HashMap<String, String>();
			map.put("datechar", dateTime.toDateTimeString("yyyy-MM-dd"));
			map.put("stationid", stationid);
			map.put("elevation", elevation);
			map.put("ldtype", ldtype);
			map.put("timechar", timechar);
			map.put("collectionName", collectionName);
			byte[] data = HttpRequest.get(DbConfig.mongoSelectUrl, map, true).bytes();
			if (data.equals("[]") || data.length <= 0) {
				serviceFilePath = "";
			} else {
				FileUtil.bytesToFile(data, serviceFilePath);
			}
		}
		return serviceFilePath;
	}

	/**
	 * 云图下载
	 *
	 * @param request
	 * @param collectionName
	 * @return
	 * @throws ParseException
	 * @author dsq
	 * @date 2018年10月18日
	 */
	private String DownLoadYt(HttpServletRequest request, String collectionName) throws ParseException {
		String fileName = "";
		String serviceFilePath = "";
		String datechar = request.getParameter("datechar").trim();
		DateTime dateTime = DateTime.parseDateTime(datechar);
		String timechar = request.getParameter("timechar").trim();
		String yttype = request.getParameter("yttype").trim();
		if (collectionName.equals("yt_file")) {
			fileName = DbConfig.getYtFileName(yttype, dateTime.toDate(), timechar);
		}
		if (collectionName.equals("yt_png_file")) {
			fileName = DbConfig.getYtFileName(yttype, dateTime.toDate(), timechar) + ".png";
		}
		if (collectionName.equals("yt_jpg_file")) {
			fileName = DbConfig.getYtFileName(yttype, dateTime.toDate(), timechar) + ".jpg";
		}

		String urlpath  ;
		if (operatingSystem.equals("Windows")){
		urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Cloud\\";// 临时文件目录
		}else {
			urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Cloud/";// 临时文件目录
		}

		serviceFilePath = urlpath + fileName;// 服务器文件

		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

		// 如果目录中不存在文件，下载雷达文件到temp目录
		File serviceFile = new File(serviceFilePath);// 服务器文件
		if (!serviceFile.exists()) {// 把文件上传到服务器
			Map<String, String> map1 = new HashMap<String, String>();
			map1.put("datechar", dateTime.toDateTimeString("yyyy-MM-dd"));
			map1.put("yttype", yttype);
			map1.put("timechar", timechar);
			map1.put("collectionName", collectionName);
			byte[] data = HttpRequest.get(DbConfig.mongoSelectUrl, map1, true).bytes();
			if (data.equals("[]") || data.length <= 0) {
				serviceFilePath = "";
			} else {
				FileUtil.bytesToFile(data, serviceFilePath);
			}
		}
		return serviceFilePath;
	}

	/**
	 * 文件下载
	 *
	 * @param request
	 * @param collectionName
	 * @param
	 * @return
	 * @author dsq
	 * @throws ParseException
	 * @date 2018年10月22日
	 */
	private String DownLoadFile(HttpServletRequest request, String collectionName, String resultType) throws ParseException {
		String fileName = "";
		String serviceFilePath = "";
		Enumeration<String> em = request.getParameterNames();
		Map<String, Object> queryMap = new HashMap<String, Object>();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			if ("collectionName".equals(name)) {
				collectionName = value;
			}
			if (!name.equals("resultType")) {// 过滤特殊字符
				queryMap.put(name, value.trim());// 去除空格
				if("datechar".equals(name)){
					fileName += DateTime.parseDateTime(value).toDateTimeString("yyyyMMddHHmmss") + "_";
				}
				else {
					fileName += value + "_";
				}
			}
		}
		String fileType = collectionName.split("_")[0];
		if (fileType.equals("image")) {
			fileType = "jpg";
		}
		if (collectionName.contains("png")) {
			fileType = "png";
		}
		if (collectionName.contains("jpg")) {
			fileType = "png";
		}
		if (collectionName.contains("bmp")) {
			fileType = "bmp";
		}
		if (fileType.equals("excel")) {
			fileType = "xlsx";
		}
		// 下载
		fileName = StringUtil.trimEnd(fileName, '_') + "." + fileType;
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/Temp/File/";
		String serviceUrl = basePath + fileName;
		String urlpath  ;
		if (operatingSystem.equals("Windows")){
			 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\File\\";
		}else {
			urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/File/";
		}

		serviceFilePath = urlpath + fileName;// 服务器文件
		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
		// 如果目录中不存在文件，下载雷达文件到temp目录
		File serviceFile = new File(serviceFilePath);// 服务器文件
		if (!serviceFile.exists()) {// 把文件上传到服务器{
			byte[] data = HttpRequest.get(DbConfig.mongoSelectUrl, queryMap, true).bytes();
			if (data.equals("[]") || data.length <= 0) {
				serviceFilePath = "";
			} else {
				if (fileType.equals("txt")) {
					try {
						FileUtil.writeLog(serviceFilePath, new String(data, FileUtil.getCodeType(data)));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				else{FileUtil.bytesToFile(data, serviceFilePath);}
			}
		}
		if ("url".equals(resultType) && !serviceFilePath.equals("")) {
			serviceFilePath = serviceUrl;
		}
		return serviceFilePath;
	}
}
